package com.breaking.second.activity.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.breaking.second.activity.BaseActivity;
import com.breaking.second.databinding.ActivityRegisterBinding;
import com.breaking.second.entity.BookEntity;
import com.breaking.second.utils.StringUtil;
import com.breaking.second.utils.okhttp.OkhttpUtil;

import okhttp3.FormBody;

//注册
public class RegisterActivity extends BaseActivity<ActivityRegisterBinding> {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        binding.register.setOnClickListener(this::register);
    }

    private void register(View view) {
        Editable mail = binding.mail.getText();
        Editable pass = binding.pass.getText();
        Editable pass1 = binding.pass1.getText();
        if (StringUtil.isEmpty(mail)) {
            Toast.makeText(this, "用户不能为空", Toast.LENGTH_SHORT).show();
        } else if (StringUtil.isEmpty(pass)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
        } else if (StringUtil.isEmpty(pass1)) {
            Toast.makeText(this, "二次密码不能为空", Toast.LENGTH_SHORT).show();
        } else if (!pass.toString().equals(pass1.toString())) {
            Toast.makeText(this, "两次密码不一样", Toast.LENGTH_SHORT).show();
        } else {
            register(mail.toString(), pass.toString());
        }
    }

    private void register(String mail, String pass) {
        FormBody.Builder form = new FormBody.Builder();
        form.add("password", pass);
        form.add("username", mail);
        OkhttpUtil.Post("user/register", form, new OkhttpUtil.CallbackListener(this::register));
    }

    private void register(BookEntity bookEntity) {
        if (bookEntity.isCode()) {
            Editable mail = binding.mail.getText();
            Editable pass = binding.pass.getText();
            if (!StringUtil.isEmpty(mail) && !StringUtil.isEmpty(pass)) {
                Intent intent = new Intent();
                intent.putExtra("mail", mail.toString());
                intent.putExtra("pass", pass.toString());
                setResult(RESULT_OK, intent);
            }
            finish();
        }
        Toast.makeText(this, bookEntity.getMsg(), Toast.LENGTH_SHORT).show();
    }


}
